package routers

import (
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"go-web/middlewares"
)

func globalMiddlewares(app *gin.Engine) {
	// 加载全局路由
	//app.Use(middlewares.HttpRecover())
	if viper.GetBool("allowCrossDomain") {
		app.Use(middlewares.AllowCrossDomain())
	}
	if viper.GetBool("aliLog.enable") {
		app.Use(middlewares.RequestLog(
			viper.GetString("aliLog.projectName"),
			viper.GetString("aliLog.logStoreName"),
			viper.GetString("aliLog.topic"),
		))
	}
	if viper.GetBool("tokenCheck.enable") {
		// 排除要检测的URL的path路径，不区分大小写
		app.Use(middlewares.TokenCheck(viper.GetStringSlice("tokenCheck.excludeCheckPath"), ""))
	}
}

// Load 加载路由
func Load(app *gin.Engine) {
	// 一定要先加载全局中间件
	globalMiddlewares(app)
	// 再加载路由中间件
	if len(routers) > 0 {
		for _, v := range routers {
			v(app)
		}
	}
}

var routers []func(app *gin.Engine)

// registry 注册路由
func registry(r func(app *gin.Engine)) {
	routers = append(routers, r)
}
